<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/9/2
 * Time: 13:58
 */
namespace App\Services;

use App\Repositories\PlatformProfitRepository;
use App\Repositories\RepaymentBillRepository;
use App\Repositories\RepaymentPlanConsumeRepository;
use App\Repositories\RepaymentPlanRepaymentRepository;
use App\Repositories\RepaymentPlanRepository;
use App\Repositories\ThreeApiErrorLogsRepository;
use App\Repositories\UserCreditCardRepository;
use App\Repositories\UserLevelPassageBankRepository;
use App\Repositories\UserLevelPassageRepository;
use App\Repositories\UserLevelRelationsRepository;
use App\Repositories\UserLevelRepository;
use App\Repositories\UserProfitRepository;
use App\Repositories\UserRepository;

class RepaymentProfitService
{
    protected $repaymentBillRepository;
    protected $repaymentPlanRepository;
    protected $repaymentPlanRepaymentRepository;
    protected $repaymentPlanConsumeRepository;
    protected $userLevelPassageRepository;
    protected $userLevelRelationsRepository;
    protected $userLevelRelationsService;
    protected $userLevelRepository;
    protected $userLevelPassageBankRepository;
    protected $userProfitRepository;
    protected $platformProfitRepository;
    protected $userRepository;
    protected $threeApiErrorLogsRepository;
    protected $cloudspSMS;
    protected $messageService;
    protected $userCreditCardRepository;
    protected $userProfitService;

    public function __construct(RepaymentBillRepository $repaymentBillRepository,
                                RepaymentPlanRepository $repaymentPlanRepository,
                                RepaymentPlanRepaymentRepository $repaymentPlanRepaymentRepository,
                                RepaymentPlanConsumeRepository $repaymentPlanConsumeRepository,
                                UserLevelPassageRepository $userLevelPassageRepository,
                                UserLevelRelationsRepository $userLevelRelationsRepository,
                                UserLevelRelationsService $userLevelRelationsService,
                                UserLevelRepository $userLevelRepository,
                                UserProfitService $userProfitService,
                                UserLevelPassageBankRepository $userLevelPassageBankRepository,
                                UserProfitRepository $userProfitRepository,
                                PlatformProfitRepository $platformProfitRepository,
                                UserRepository $userRepository,
                                ThreeApiErrorLogsRepository $threeApiErrorLogsRepository,
                                CloudspSMS $cloudspSMS,
                                MessageService $messageService,
                                UserCreditCardRepository $userCreditCardRepository)
    {
        $this->repaymentBillRepository = $repaymentBillRepository;
        $this->repaymentPlanRepository = $repaymentPlanRepository;
        $this->repaymentPlanRepaymentRepository = $repaymentPlanRepaymentRepository;
        $this->repaymentPlanConsumeRepository = $repaymentPlanConsumeRepository;
        $this->userLevelPassageRepository = $userLevelPassageRepository;
        $this->userLevelRelationsRepository = $userLevelRelationsRepository;
        $this->userLevelRelationsService = $userLevelRelationsService;
        $this->userLevelRepository = $userLevelRepository;
        $this->userLevelPassageBankRepository = $userLevelPassageBankRepository;
        $this->userProfitRepository = $userProfitRepository;
        $this->platformProfitRepository = $platformProfitRepository;
        $this->userRepository = $userRepository;
        $this->threeApiErrorLogsRepository = $threeApiErrorLogsRepository;
        $this->cloudspSMS = $cloudspSMS;
        $this->messageService = $messageService;
        $this->userCreditCardRepository = $userCreditCardRepository;
        $this->userProfitService = $userProfitService;
    }

    public function repaymentC($param)
    {
        //更新还款状态
        if ($param['order_status'] == 'SUCCESS') {
            echo 'SUCCESS';
            $this->repaymentSuccess($param['mch_no']);
        } else {
            $message = $param['fail_message'];
            $this->repaymentFail($param['mch_no'], $message);
        }
        $errorData = [
            'order_no' => $param['mch_no'],
            'error_code' => $param['order_status'],
            'error_msg' => json_encode($param),
            'api_type' => 7
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
    }

    public function repaymentE($param)
    {
        //更新还款状态
        if ($param['order_status'] == 'SUCCESS') {
            echo 'SUCCESS';
            $this->repaymentSuccess($param['mch_no']);
        } else {
            $message = $param['fail_message'];
            $this->repaymentFail($param['mch_no'], $message);
        }
        $errorData = [
            'order_no' => $param['mch_no'],
            'error_code' => $param['order_status'],
            'error_msg' => json_encode($param),
            'api_type' => 20
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
    }

    public function repaymentSuccess($orderNo)
    {
        $repaymentPlan = $this->repaymentPlanRepaymentRepository->findByPlanRepaymentSn($orderNo);
        if ($repaymentPlan->repayment_every_status > 3001) {
            die('SUCCESS');
        }
        $this->repaymentPlanRepaymentRepository->updateStatusByPlanRepaymentSn($orderNo, 3002);//成功
        $plan = $this->repaymentPlanRepository->byId($repaymentPlan->repayment_plan_id);
        //发送还款成功消息提醒
        $userOwn = $this->userRepository->byId($plan->user_id);
        $creditCard = $this->userCreditCardRepository->isExistUserBankNo($plan->user_id, $repaymentPlan->bank_no);
        $this->messageService->messageTemplate(12, $userOwn->invited_code, $creditCard->bank_no, $creditCard->bank_description,
            $repaymentPlan->repayment_every_time_money, '', '', $repaymentPlan->repayment_plan_id, '', '');
        //是否是计划的最后一天，则完成计划
        if (date('Y-m-d') == date('Y-m-d', $plan->finish_plan_time)) {
            $plan->update([
                'update_plan_time' => time(),
                'repayment_plan_status' => 1002,//成功
            ]);
            //您的尾号{1}订单{2}已执行完毕，感谢您使用龙猫管家，祝您生活愉快！回T退订
            $content = substr($repaymentPlan->bank_no, -4) . '##' . $orderNo;
            $user = $this->userRepository->byId($plan->user_id);
            $this->cloudspSMS->sendSMSNotify($user->mobile, $content, 'successOrder', 7);
            //账单金额与还款金额相同更新账单为已还清
            $bill = $this->repaymentBillRepository->byId($plan->repayment_bill_id);
            if ($bill->repayment_bill_money == $plan->repayment_money) {
                $bill->update([
                    'bill_status' => 3 //账单状态：0待出账 1待更新 2待还清 3已还清 4已逾期
                ]);
            }
            //发送还款成功消息提醒
            $creditCard = $this->userCreditCardRepository->isExistUserBankNo($plan->user_id, $repaymentPlan->bank_no);
            $this->messageService->messageTemplate(1, $user->invited_code, $creditCard->bank_no, $creditCard->bank_description,
                $plan->repayment_money, '', '', $repaymentPlan->repayment_plan_id, '', '');
        }
    }

    protected function repaymentFail($orderNo, $messageFail)
    {
        $repaymentPlan = $this->repaymentPlanRepaymentRepository->findByPlanRepaymentSn($orderNo);
        if ($repaymentPlan->repayment_every_status > 3001) {
            die('SUCCESS');
        }
        //更新还款状态为失败
        $this->repaymentPlanRepaymentRepository->updateStatusByPlanRepaymentSn($orderNo, 3003, $messageFail);//失败
        $plan = $this->repaymentPlanRepository->byId($repaymentPlan->repayment_plan_id);
        //更新计划为失败
        $plan->update([
            'update_plan_time' => time(),
            'repayment_plan_status' => 1003,//失败
        ]);
        $repaymentJobs = new RepaymentPlanJobsService();
        //失败提现
        $repaymentJobs->intoRepaymentAutoWithdrawJobs($repaymentPlan->repayment_passage_id, $plan->user_id, $repaymentPlan->repayment_plan_id, $repaymentPlan->id);
        //发送还款失败消息提醒
        $userOwn = $this->userRepository->byId($plan->user_id);
        $creditCard = $this->userCreditCardRepository->isExistUserBankNo($plan->user_id, $repaymentPlan->bank_no);
        $this->messageService->messageTemplate(2, $userOwn->invited_code, $creditCard->bank_no, $creditCard->bank_description,
            $repaymentPlan->repayment_every_time_money, '', '', $repaymentPlan->repayment_plan_id, '', '');
        //您的尾号{1}订单{2}执行失败！请重新制定计划。回T退订
        $content = substr($repaymentPlan->bank_no, -4) . '##' . $orderNo;
        $user = $this->userRepository->byId($plan->user_id);
        $this->cloudspSMS->sendSMSNotify($user->mobile, $content, 'failOrder', 8);
    }

    public function profit($orderNo, $money, $consumeServiceCharge, $passageId, $fromUserId, $bankCode, $beProfitUserMobile)
    {
        //找出上两级会员
        $userLevelRelationsService = $this->userLevelRelationsService->getUserLevelRelations($fromUserId);
        $userLevelPassageThree = $this->userLevelPassageRepository->first($passageId, $userLevelRelationsService['three']['level_id']);
        $supplyPercent = 0;
        if ($userLevelPassageThree->type == 0) {
            $supplyPercent = $userLevelPassageThree->supply_percent;//成本价
        }
        if ($userLevelPassageThree->type == 1) {
            $userLevelPassageBank = $this->userLevelPassageBankRepository->passageToBank($passageId, $bankCode, $userLevelRelationsService['three']['level_id']);
            $supplyPercent = $userLevelPassageBank->supply_percent;//成本价
        }
        $profit = $consumeServiceCharge - $userLevelPassageThree->second_rate;
        $cost = round($money * $supplyPercent);//成本价
        if (!empty($userLevelRelationsService)) {
            //直接收益
            if (!empty($userLevelRelationsService['two'])) {
                if ($userLevelRelationsService['two']['level_id'] <= 2) {
                    $directProfit = $this->userProfitService->userProfit($userLevelRelationsService['two']['level_id'], $money, $userLevelPassageThree->rate,
                        2, $passageId, $bankCode, $beProfitUserMobile, $orderNo, $profit, $fromUserId,
                        $userLevelRelationsService['two']['user_id'], 7, 0);
                    $directToUserId = $userLevelRelationsService['two']['user_id'];
                } else {
                    $directProfit = 0;
                    $directToUserId = 0;
                }
            } else {
                $directProfit = 0;
                $directToUserId = 0;
            }
            //间接收益
            if (!empty($userLevelRelationsService['one'])) {
                if ($userLevelRelationsService['one']['level_id'] <= 2) {
                    $indirectProfit = $this->userProfitService->userProfit($userLevelRelationsService['one']['level_id'], $money, $userLevelPassageThree->rate,
                        2, $passageId, $bankCode, $beProfitUserMobile, $orderNo, $profit, $fromUserId,
                        $userLevelRelationsService['one']['user_id'], 7, 1);
                    $indirectToUserId = $userLevelRelationsService['one']['user_id'];
                } else {
                    $indirectProfit = 0;
                    $indirectToUserId = 0;
                }
            } else {
                $indirectProfit = 0;
                $indirectToUserId = 0;
            }
            //平台收益
            $platformProfit = $consumeServiceCharge - $directProfit - $indirectProfit - $cost;
            $data = [
                'bill_no' => makeOrderNo(),
                'from_profit_sn' => $orderNo,
                'revenue_money' => $consumeServiceCharge,//手续费+秒到费
                'profit_money' => $platformProfit,//手续费+秒到费-两层级分润-成本
                'cost_money' => $cost,//成本
                'pen_num' => 1,//消费笔数
                'from_user_id' => $fromUserId,
                'direct_to_user_id' => $directToUserId,
                'direct_profit_money' => $directProfit,
                'indirect_to_user_id' => $indirectToUserId,
                'indirect_profit_money' => $indirectProfit,
                'profit_type' => 2,//收益类型： 1好友升级 2好友还款 3好友收款 4交易返现 5办理贷款 6办信用卡
                'create_time' => time(),
                'create_month' => date('Y-m'),
            ];
            $this->platformProfitRepository->create($data);
        }

    }
}